package com.bilicraft.plugin.kexue.utils;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import org.bukkit.command.CommandSender;

/** for '_get' command*/
public class Download implements Runnable{
	public URL url;
	public String filename;
	
	public CommandSender commandSender;
	
	public int curSize;
	public boolean finish;
	
	private FileOutputStream fos;
	private BufferedInputStream bis;
	HttpURLConnection huc;
	
	public Download(String src, String fname, CommandSender sender){
		try{
			commandSender = sender;
			url = new URL(src);
			filename = fname;
			curSize = 0;
			finish = false;
			Thread t = new Thread(this);
			t.start();
		}catch(Exception e){
			commandSender.sendMessage("- get "+filename + ":failed");
		}
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		try{
			download();
		}catch(Exception e){
			commandSender.sendMessage("- get "+filename + ":failed");
		}
	}
	
	public void download() throws IOException {
	    byte[] buf = new byte[1048576];
	    int size = 0;
	    huc = (HttpURLConnection) url.openConnection();
	    huc.connect();
	    bis = new BufferedInputStream(huc.getInputStream());
	    fos = new FileOutputStream(filename);
	    commandSender.sendMessage("Download starting...");
	    commandSender.sendMessage("- connecting:"+url);
	    while ( (size = bis.read(buf)) != -1){ 
	      fos.write(buf, 0, size);
	      curSize += size;
	      commandSender.sendMessage("- finish:"+curSize+"bytes");
	    };
	    commandSender.sendMessage("Download finished.");
	    fos.close();
	    bis.close();
	    huc.disconnect();
	    finish = true;
	  }
}